<?php
/**
 * 根据传入的域名做初始化工作
 *
 * @author hzjsq@msn.com
 * @version 1.0
 */

//$argv[1] = 't12.fh.taoex.com';
//$argv[2] = 15;
//$argv[3] = 15;

$domain = $argv[1];
$order_id = $argv[2];
$host_id = $argv[3];

if (empty($domain) || empty($order_id) || empty($host_id)) {

	die('No Params');
}

set_time_limit(0);
define('initDB', '/data/initDatabase.sql');

define('DB_USER', 'queue');
define('DB_PASSWORD', 'queue_zova');
define('COMMAND_MODE', true);

require_once(dirname(__FILE__) . '/lib/init.php');

$db = kernel::database();
//创建数据库
$db->query(sprintf('CREATE DATABASE %s CHARACTER SET utf8 ;', DB_NAME));
$db->query(sprintf('USE %s', DB_NAME));

$db->query(sprintf("GRANT ALL PRIVILEGES ON %s.* TO '%s'@'192.168.%%.%%' IDENTIFIED BY '%s'", DB_NAME, DB_REAL_USER, DB_REAL_PASSWORD));
$db->query("FLUSH PRIVILEGES");

ilog("Create database user informatin done. (UserName => ".DB_REAL_USER.",PassWord => ".DB_REAL_PASSWORD.").");

//导入初始数据
importData();

//$db->query(sprintf('UPDATE sdb_base_kvstore SET value=\'%s\' WHERE key=\'banner\' and prefix=\'setting/desktop\'', mysql_escape_string('s:120:"<img src=\'/app/omestart/static/images/logo.jpg\' border=\'0\' height=\'25\' width=\'94\'><sup style=\'font-size:9px;\'>beta</sup>";')));
ilog("Import database OK.");
cachemgr::init(false);
kernel::single('base_shell_webproxy')->exec_command('cacheclean');
kernel::single('base_shell_webproxy')->exec_command('kvstorerecovery');

//设置mapp
/*$app_info = array(
    "exclusion" => "true",
    "value" => "true",
    "app_id" => "omestart"
);
app::get('base')->setConf('system.main_app', $app_info);*/
kernel::single('base_shell_webproxy')->exec_command("update --ignore-download");
ilog("Update Ok.");
$db = kernel::database();
//清除发货单模板，重新加入新模板
$db->exec("DELETE FROM sdb_ome_print_tmpl");
_default_dlytpl();

kernel::single('base_certificate')->register(sprintf('http://%s',$domain));
//更新SASS信息
if (!class_exists('SaasOpenClient', false)) {

	require_once(ROOT_DIR . "/config/saasapi.php");
}

$api = new SaasOpenClient();
$api->appkey = SASS_APP_KEY;
$api->secretKey = SAAS_SECRE_KEY;
$api->format = 'json';

//应用证书号
$certi_id = kernel::single('base_certificate')->certi_id();
//应用节点号
$node_id = kernel::single('base_shopnode')->node_id('ome');

$params = array('order_id' => $order_id, 'host_id' => $host_id, 'certi_id' => $certi_id, 'node_id' => $node_id);


$retryNum = 0;

while($retryNum < 3) {

	$result = $api->execute('host.active', $params);
	if ($result->success != 'true') {

		$retryNum ++;
		ilog("Call SASS center interface failed, Retry $retryNum numbers . (OrderId=>$order_id,HostId=>$host_id).");
		usleep(5000);
	} else {

		$retryNum += 100;
		ilog("Call SASS center interface is OK (OrderId=>$order_id,HostId=>$host_id).");
	}
}

//开始参数配置
/*app::get('omestart')->setconf('send_weight', 'N');
app::get('omestart')->setconf('ome.delivery.consign', 'N');
app::get('omestart')->setconf('ome.delivery.useCheck', 'Y');
app::get('omestart')->setconf('ome.delivery.useSend', 'Y');
app::get('omestart')->setconf('ome.delivery.autoSend', 'Y');
ilog("Send params is set finished.");

$printSet= array('set' => array('delie' => '0', 'expre' => '1', 'stock' => '0', 'ome_batch_print_nums' => '100', 'ome_delivery_is_printstock' => '2', 'ome_delivery_is_printdelivery' => '2', 'ome_delivery_is_printship' => '2', 'printMode' => 'activex'));
app::get('ome')->setConf('ome.delivery.status.cfg', $printSet);
ilog("Printer params is set finished.");*/

$db->query('UPDATE sdb_pam_account SET login_password=\'' . md5(DB_REAL_PASSWORD) . '\' WHERE login_name=\'admin\' AND account_type=\'shopadmin\'');
//app::get('omestart')->setconf('createFirstRun', 'y');

//ilog("First Run params is set finished.");

ilog("Active process finished.");

/**
 * 更新物流信息
 */
function _default_dlytpl(){
    $dlytpl_dir = ROOT_DIR."/app/ome/initial/dlytpl/";

    if($handle = opendir($dlytpl_dir)){
        while(false !== ($dtp = readdir($handle))){
            $path_parts = pathinfo($dtp);
            if($path_parts['extension'] == 'dtp'){
                $file['tmp_name'] = ROOT_DIR."/app/ome/initial/dlytpl/".$dtp;
                $file['name'] = $dtp;
                $result = kernel::single("ome_print_tmpl")->upload_tmpl($file);
            }
        }

        closedir($handle);
    }
}


/**
 * 导入数据，格式为 SQLyog 导出的SQL文件格式
 */
function importData() {

    $fp = fopen(dirname(__FILE__) . initDB, 'r');

    if ($fp) {
        $sql =  '';
        while($line = fgets($fp)) {

           $sql .= $line;
           if (preg_match('/;[\n\r\t]{0,}$/is', $line)) {

               if (preg_match('/\*\/[\n\r\t]{0,}$/is', $line)) {

                   $sql = '';
               } else {
                   //$sql = preg_replace('', '', $sql);
                   kernel::database()->query($sql);
                   $sql = '';
               }
           }elseif (preg_match('/\*\/[\n\r\t]{0,}$/is', $line)) {

               $sql = '';
           }
        }

        fclose($fp);
    } else {

        ilog("Can't open Init SQL file");
    }
}


/**
 * 日志
 */
function ilog($str) {

	global $domain;
	$filename = dirname(__FILE__) . '/logs/' . date('Y-m-d') . '.log';
	$fp = fopen($filename, 'a');
	fwrite($fp, date("m-d H:i") . "\t" . $domain . "\t" . $str . "\n");
	fclose($fp);
}